
/**
 *
 * @param {(resolve, reject)=>void} task
 */
function Promise(task) {
    this._catchCallback = null
    this.thenCallbacks = []
    this.awaitThen= false;
    this.lastResult = null
    this.then = callback => {
        this.thenCallbacks.push(callback)
        if(this.awaitThen){
           this.lastResult =  callback(this.lastResult);
        }
        return this
    }
    this.catch = callback => {
        this._catchCallback = callback
        return this
    }
    const resolve = val => {
        this.awaitThen = true;
        this.lastResult = val
        if (this.thenCallbacks.length === 0)
        return
        for (let callback of this.thenCallbacks) {
            this.lastResult = callback(this.lastResult)
        }
    }
    const reject = err => {
        if (this._catchCallback !== null) {
            this._catchCallback(err)
        }
    }
    task(resolve, reject)
}
